import { log } from 'cc';
import { BaseJSBridge } from './BaseJSBridge'
import { BridgeClientMethods } from '../CconfigClient';


/** 合并类型，让 JSBridgeClient 实例拥有所有方法签名 */
export interface JSBridgeClient<BP extends Record<string, any>> extends BridgeClientMethods { }


export class JSBridgeClient<BP extends Record<string, any>> extends BaseJSBridge<{}> {
    constructor(private routes: { [K in keyof BP]: string }) {
        super();
        Object.entries(this.routes).forEach(([methodName, route]) => {
            Object.defineProperty(this, methodName, {
                value: (payload: any = {}) => {
                    this.callHandler(route, payload);
                }
            });
        });
    }

    private callHandler(name: string, params: any = {}) {
        log('platform', name, params)
        if (this.isAndroid) {
            (window as any)?.WebViewJavascriptBridge?.callHandler(name, params, () => {
                // 处理安卓返回的数据
                log('Response from Android:');
            })
        } else if (this.isIOS) {
            setupWKWebViewJavascriptBridge((bridge: any) => {
                bridge.callHandler(name, params, () => {
                    log('Response from IOS:');
                })
            })
        } else {
            window.parent.postMessage(JSON.stringify({ type: name, data: params }), "*");
        }
    }

}

const setupWKWebViewJavascriptBridge = (callback: (bridge: any) => void) => {
    const _win: any = window
    if (_win?.WKWebViewJavascriptBridge) {
        return callback(_win.WKWebViewJavascriptBridge);
    }
    if (_win?.WKWVJBCallbacks) {
        return _win.WKWVJBCallbacks.push(callback);
    }
    _win.WKWVJBCallbacks = [callback];
    _win.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null)
}

